<template>
  <div class="page product-index">
    <van-nav-bar title="提交订单" left-text="返回" left-arrow @click-left="onClickLeft" />
<!--:clickable="true" -->
      <van-grid v-if="products[0].type!=3"  :column-num="2">
          <van-grid-item :class="radio==1?'order':'order1'" @click="radio=1">外送取货</van-grid-item>
          <van-grid-item :class="radio==2?'store':'store1'" @click="radio=2" >门店自取</van-grid-item>
      </van-grid>
      <van-grid v-if="products[0].type==3" :column-num="1">
          <van-grid-item class="order" >预约商品</van-grid-item>
      </van-grid>

   <!--外送选择-->
  <van-cell
     v-show="codes"
     class="address-item margin-top"
     size="large"
     icon="location-o"
     is-link
     @click="onSelect"
   >
     <div v-if="address && address.address_id > 0" class="has-address">
       <div class="address-name">{{address.recive_name}}, {{address.mobile}}</div>
       <div
         class="address-vice"
       >{{address.province}} {{address.city}} {{address.area}} {{address.address}}</div>
     </div>
     <div v-else class="no-address">请选择地址</div>
   </van-cell>
      <!--门店选择 -->
      <van-cell
               v-show="code"
               class="address-item margin-top"
               size="large"
               icon="location-o"
               is-link
               @click="onSelects"
      >
          <div class="has-address">
              <div style="  margin-top:1.5rem;  display: flex;justify-content: space-between" class="address-vice">
                  <div class="address-name">{{store_list[i].contact_name}}, {{store_list[i].contact_tel}}</div>
                  <div>{{store_list[i].distance>=1000?(Math.round(store_list[i].distance/100)/10).toFixed(1)+'km': store_list[i].distance+'m'}}</div>
              </div>
              <div>{{store_list[i].contact_address}},{{store_list[i].store_name}}</div>

          </div>
      </van-cell>
      <!--预约商品 -->
      <van-cell
              v-show="make"
              class="address-item margin-top"
              size="large"
              icon="location-o"
              is-link
              @click="onSelects"
      >
          <div class="has-address">
              <div style=" margin-top:1.5rem;  display: flex;justify-content: space-between" class="address-vice">
                  <div class="address-name">{{store_list[i].contact_name}}, {{store_list[i].contact_tel}}</div>
                  <div>{{store_list[i].distance>=1000?(Math.round(store_list[i].distance/100)/10).toFixed(1)+'km': store_list[i].distance+'m'}}</div>
              </div>
              <div>{{store_list[i].contact_address}},{{store_list[i].store_name}}</div>

          </div>
      </van-cell>


<!--订单详情-->
    <van-panel class="margin-top">
      <van-card
        v-for="item in products"
        :key="item.sku_id"
        :num="item.count"
        :price="item.price"
        :desc="getSpecData(item)"
        :title="item.product_title"
        :thumb="item.product_image"
      />
    </van-panel>

      <div  v-show="make">
          <van-cell  title="姓名"  @click="paymentinput" :value="payment_input==''?'请填写姓名':payment_input"></van-cell>
          <van-cell  title="电话"  @click="paymenttel" :value="payment_tell==''?'请填写电话':payment_tell"></van-cell>
      </div>

      <van-popup v-model="payment" position="bottom" :style="{ height: '15%' }" >
          <van-cell-group>
              <van-field  ref="atlas-name-input"   v-model="payment_input" label="姓名" id='inputId' placeholder="请输入姓名" />
          </van-cell-group>
      </van-popup>

      <van-popup v-model="paymentte" position="bottom" :style="{ height: '15%' }" >
          <van-cell-group>
              <van-field  ref="atlas-name-tel" v-model="payment_tell" type="tel" label="请输入手机号" />
          </van-cell-group>
      </van-popup>




<!--    &lt;!&ndash;支付方式 &ndash;&gt;-->
<!--    <van-radio-group v-model="radio">-->
<!--      <van-cell-group>-->
<!--        <van-cell disabled title="在线支付" clickable @click="radio = '1'">-->
<!--          <template #right-icon>-->
<!--            <van-radio name="1" />-->
<!--          </template>-->
<!--        </van-cell>-->
<!--        <van-cell title="到店支付" clickable @click="radio = '2'">-->
<!--          <template #right-icon>-->
<!--            <van-radio name="2" />-->
<!--          </template>-->
<!--        </van-cell>-->
<!--        <van-cell title="货到付款" clickable @click="radio = '3'">-->
<!--          <template #right-icon>-->
<!--            <van-radio name="3" />-->
<!--          </template>-->
<!--        </van-cell>-->
<!--      </van-cell-group>-->
<!--    </van-radio-group>-->

<!--    <div class="margin-top">-->
<!--      <van-cell title="邮费" :value="express.fee>0?express.fee:'免费包邮'"></van-cell>-->
<!--    </div>-->

    <van-submit-bar :price="price" button-text="提交订单" @submit="onSubmit" />
    <!-- 联系人列表 -->
    <van-popup v-model="showList" position="bottom">
      <div v-if="list">
        <address-list
          :lists="list"
          :selected-id="address?address.address_id:0"
          @pick="pickAddress"
        />
        <div class="text-center" style="padding:20px 0;">
<!--          <van-button v-if="isWechat" plain type="primary" @click="importAddress">从微信导入地址</van-button>-->
          <van-button plain type="primary" @click="manageAddress">管理地址</van-button>
          <van-button class="margin-left" type="info" plain @click="addAddress">添加地址</van-button>
        </div>
      </div>
      <div v-else class="empty-box">
        <van-loading size="24px">加载中...</van-loading>
        <div style="margin-top:50px;"></div>
      </div>
    </van-popup>
<!--门店选择-->

      <van-popup class="popup" v-model="showLists" position="bottom" >
          <div v-for="(list,i) in store_list"  :key='i'>
              <van-cell :title="list.contact_name" :value="list.distance>=1000?(Math.round(list.distance/100)/10).toFixed(1)+'km': list.distance+'m'" size="large" :label="list.contact_address+','+list.store_name" @click="can_cell(list.id)" />
          </div>
      </van-popup>
  </div>
</template>
<script>
import utils from "../../utils";
import config from "../../config";
import upsdk from "upsdk-vue";
// import api from "@/api";

export default {
  data() {
    return {
         //列表
         listet: [],
         loading: false,
         finished: false,
         store_list:[],
         //默认选择第一个
         i:0,
         //显示隐藏
         code:true,
         codes:true,
         make:true,
         //支付方式
         radio: 1,
         from:'quick',
         sku_id: 0,
         initCount:1,
         products: [],
         address_id: 0,
         address: {},
         express: { title: "", fee: 0 },
         showList: false,
         showLists:false,
         list: null,
         isWechat: config.isWechat && config.wxid,
         tn:"",
         id:"",
        // window.localStorage.getItem("lat")
        lat:"",
        lng: "",
        payment_input:"",
        payment_tell:"",
        payment:false,
        paymentte:false,

    };
  },
    watch: {
    //选择支付方式
    radio:{
      handler (radio) {
        // console.log(radio)
          if(radio==2){
           this.code=true
            this.codes=false
              this.make=false
          }else if(radio==1){
            this.code=false
            this.codes=true
            this.make=false
          }else if(radio==3){
              this.code=false
              this.codes=false
              this.make=true
          }

      },
      immediate: true
    }
  },
  computed: {
    price() {
      let total_price = 0;
      this.products.map(item => {
        total_price += item.price * item.count;
      });
      return Math.round(total_price * 100);
    }
  },
  mounted() {
    let params = this.$route.query;
    console.log(params);
    if (!this.sku_id && !params.sku_id) {
      this.$toast.fail("产品资料错误");
      this.$router.back();
    }
    this.sku_id = params.sku_id;

    if (params.count) {
      this.initCount = params.count;
    }
    if (params.address_id) {
      this.address_id = params.address_id;
    }
    if (params.from) {
      this.from = params.from;
    }
    if (!window.localStorage.getItem("lat") || !window.localStorage.getItem("lng")){
        this.lat=1.4455;
        this.lng=1.43434;
    }else{
        this.lat=window.localStorage.getItem("lat");
        this.lng=window.localStorage.getItem("lng");
    }

    this.prepare();
    // this.module()
      this.geography()



  },
  methods: {
      //点击填写姓名
      paymentinput(){
              this.payment=true;
              this.$nextTick(()=>{ //自动获取焦点 element组件autofocus失效
                  this.$refs['atlas-name-input'].$refs.input.focus()
              })
      },
      //点击填写电话
      paymenttel(){
          this.paymentte=true;
          this.$nextTick(()=>{ //自动获取焦点 element组件autofocus失效
              this.$refs['atlas-name-tel'].$refs.input.focus()
          })
      },
      //  获取当前位置
      geography(){
          this.$api
              .post("order/selectStore", {
                  lat:this.lat,
                  lng:this.lng
              })
              .then(json => {
                this.store_list=json.data

              })
      },
    onClickLeft() {
      this.$router.back();
    },
    skuid2Obj(ids){
      let idArr=ids.toString().split(',')
      return idArr.map(value=>{
        return {
          sku_id:parseInt(value)
        }
      })
    },
    prepare() {
      this.$api
        .post("order/prepare", {
          products: this.from=='cart'?this.skuid2Obj(this.sku_id):[{ sku_id: this.sku_id, count: this.initCount }],
          address: this.address_id,
          from: this.from
        })
        .then(json => {
          this.products = utils.fixListImage(json.data.products,'product_image');
          if (json.data.address) this.address = json.data.address;
          this.express = json.data.express;
          if (this.products[0].type==3){
              this.radio=3;
          }

        })
        .catch(err => {
          this.$toast.fail(err.msg || "产品资料错误");
          this.$router.back();
        });
    },

    getSpecData(item){
      if(!item.spec_data || item.spec_data.length<1){
        return item.goods_no
      }
      let desc = [];
      for(let i in item.specs){
        desc.push(item.spec_data[i].title+': '+item.specs[i])
      }
      return desc.join(';')
    },
    onSelect() {
      this.showList = true;
      if (this.showList && !this.list) {
        this.loadAddress();
      }
    },
      //门店取货选择
      onSelects() {
          this.showLists = true;
              this.geography();
      },
      can_cell(id){
          this.showLists = false;
          this.i=id-1;
      },
    loadAddress() {
      this.$api
        .get("member.address/index")
        .then(json => {
          this.list = json.data;
        })
        .catch(err => {
          this.$toast.fail(err.msg || "地址资料加载失败");
        });
    },
    pickAddress(address) {
      //console.log(address)
      this.showList = false;
      this.address = address;
    },
    manageAddress() {
      this.$router.push("/member/address");
    },
    addAddress() {
      this.$router.push("/member/address/detail");
    },
    // importAddress() {
    //   this.$api.wechatReady(wx => {
    //     wx.openAddress({
    //       success: res => {
    //         var address = {};
    //         address.recive_name = res.userName;
    //         //address.recive_name = res.postalCode
    //         address.province = res.provinceName;
    //         address.city = res.cityName;
    //         address.area = res.countyName;
    //         address.address = res.detailInfo;
    //         //address.recive_name = res.nationalCode
    //         address.mobile = res.telNumber;
    //         //address.id = 0

    //         this.$api
    //           .post("member.address/save", { address: address, id: 0 })
    //           .then(json => {
    //             if (json.code == 1) {
    //               this.$toast.success("保存成功");
    //               this.loadAddress();
    //             }
    //           })
    //           .catch(error => {
    //             this.$toast.fail(error.msg || "保存失败");
    //           });
    //       }
    //     });
    //   });
    // },
    onSubmit() {
      // if (!this.address || !this.address.address_id) {
      //   this.$toast.fail("请选择收货地址");
      //   return;
      // }
      this.$dialog
        .confirm({
          title: "确认下单",
          message: "确认下单支付?"
        })
        .then(() => {
          this.doSubmit();
        });
    },

    //  引入外部文件
    //   module(){
    //     // var module = require('./module.js');
    //     // async function main() {
    //       // var dd = await module('https://open.95516.com/s/open/js/upsdk.js');
    //       // var upsdk = dd.qs();
    //       // console.log(upsdk);
    //       //初始化获取到的数据
    //       // let list= window.location.href
    //       // console.log(list)
    //
    //       // api.post('/auth/config',{
    //       //   url:list
    //       // }).then(json => {
    //       //   upsdk.config({
    //       //     appId:json.data.appId,// 必填，接入方的唯一标识
    //       //     timestamp:Number(json.data.timestamp) , // 必填，生成签名的时间戳
    //       //     nonceStr: json.data.nonceStr, // 必填，生成签名的随机串
    //       //     signature:json.data.signature,// 必填，签名因子包括 appId、frontToken、nonceStr、
    //       //     debug: json.data.debug // 开发阶段可打开此标记，云闪付APP会将调试信息toast
    //       //
    //       //   });
    //       // });
    //     // }
    //     // main();//执行文件
    //   },

    // appid(){
    //
    // },


    //下单
    doSubmit(){
      this.$toast.loading();
        if (this.radio==1){
            if (!this.address || !this.address.address_id){
                this.$toast.fail("请选择地址后提交订单");
            }else{
                this.$api
                    .post("order/confirm", {
                        products: this.from=='cart'?this.skuid2Obj(this.sku_id):[{ sku_id: this.sku_id, count:  this.initCount }],
                        //收货地址
                        store_id:this.store_list[this.i].id,
                        address_id:this.address.address_id,
                        from:this.from,
                        take_type:this.radio,
                        lat:this.lat,
                        lng:this.lng,
                        //金额
                        total_price: this.price / 100
                    })
                    .then(json => {
                        //下单成功
                        if (json.code == 1) {
                            let order_id = json.data.order_id;
                            this.id=json.data.order_id;
                            this.tn = json.data.tn;
                            if(!order_id){
                                return;
                            }
                            //
                            // if (this.radio==2) {
                            //     this.$toast.success("下单成功请尽快前往门店支付");
                            //     this.$router.replace("/member/order/detail?id=" +  this.id);
                            // }else{
                            upsdk.pay({
                                tn: this.tn,
                                success: function(res){
                                    this.$router.push("/member/order/detail?id=" + this.id);
                                    this.$toast.fail(res.msg);
                                },
                                fail: function(err){
                                    console.log(err)
                                }
                            });
                            // }

                            // this.$toast.success(json.msg);

                            // if(json.data.payed){
                            //   this.$router.replace("/member/order/detail?id=" + order_id);
                            //   return;
                            // }
                            // this.$api.upPay(json.data.tn,order_id).then(()=>{
                            //   console.log("调用成功")
                            // }).catch(()=>{
                            //   console.log("调用失败")
                            // })

                            // this.$api.wxPay(order_id,'').then(()=>{
                            //   this.$router.replace("/member/order/detail?id=" + order_id);
                            // }).catch(()=>{
                            //   this.$router.replace(
                            //     "/member/order/detail?id=" + order_id
                            //   );
                            // })
                        }
                    })
            }

        }else  if(this.radio==2){
            this.$api
                .post("order/confirm", {
                    products: this.from=='cart'?this.skuid2Obj(this.sku_id):[{ sku_id: this.sku_id, count:  this.initCount }],
                    //收货地址
                    store_id:this.store_list[this.i].id,
                    from:this.from,
                    take_type:this.radio,
                    //金额
                    lat:this.lat,
                    lng:this.lng,
                    total_price: this.price / 100
                })
                .then(json => {
                    //下单成功
                    if (json.code == 1) {
                        let order_id = json.data.order_id;
                        this.id=json.data.order_id;
                        this.tn = json.data.tn;
                        if(!order_id){
                            return;
                        }
                        // if (this.radio==2) {
                        //     this.$toast.success("下单成功请尽快前往门店支付");
                        //     this.$router.replace("/member/order/detail?id=" +  this.id);
                        // }else{
                            upsdk.pay({
                                tn: this.tn,
                                success: function(res){
                                    this.$router.push("/member/order/detail?id=" + this.id);
                                    this.$toast.fail(res.msg);
                                },
                                fail: function(err){
                                    console.log(err)
                                }
                            });
                        // }

                        // this.$toast.success(json.msg);
                        // if(json.data.payed){
                        //   this.$router.replace("/member/order/detail?id=" + order_id);
                        //   return;
                        // }
                        // this.$api.upPay(json.data.tn,order_id).then(()=>{
                        //   console.log("调用成功")
                        // }).catch(()=>{
                        //   console.log("调用失败")
                        // })


                        // this.$api.wxPay(order_id,'').then(()=>{
                        //   this.$router.replace("/member/order/detail?id=" + order_id);
                        // }).catch(()=>{
                        //   this.$router.replace(
                        //     "/member/order/detail?id=" + order_id
                        //   );
                        // })
                    }
                })
        }else  if(this.radio==3 ){
            if (this.payment_input=='' || this.payment_tell==''){
                this.$toast.fail("请输入姓名电话");
            }else{
                this.$api
                    .post("order/confirm", {
                        products: this.from=='cart'?this.skuid2Obj(this.sku_id):[{ sku_id: this.sku_id, count:  this.initCount }],
                        //收货地址
                        store_id:this.store_list[this.i].id,
                        from:this.from,
                        is_subscribe:1,
                        recive_name:this.payment_input,
                        mobile:this.payment_tell,
                        take_type:2,
                        //金额
                        lat:this.lat,
                        lng:this.lng,
                        total_price: this.price / 100
                    })
                    .then(json => {
                        //下单成功
                        if (json.code == 1) {
                            let order_id = json.data.order_id;
                            this.id=json.data.order_id;
                            this.tn = json.data.tn;
                            if(!order_id){
                                return;
                            }

                            // if (this.radio==2) {
                            //     this.$toast.success("下单成功请尽快前往门店支付");
                            //     this.$router.replace("/member/order/detail?id=" +  this.id);
                            // }else{
                            upsdk.pay({
                                tn: this.tn,
                                success: function(res){
                                    this.$router.push("/member/order/detail?id=" + this.id);
                                    this.$toast.fail(res.msg);
                                },
                                fail: function(err){
                                    console.log(err)
                                }
                            });
                            // }

                            // this.$toast.success(json.msg);
                            // if(json.data.payed){
                            //   this.$router.replace("/member/order/detail?id=" + order_id);
                            //   return;
                            // }
                            // this.$api.upPay(json.data.tn,order_id).then(()=>{
                            //   console.log("调用成功")
                            // }).catch(()=>{
                            //   console.log("调用失败")
                            // })


                            // this.$api.wxPay(order_id,'').then(()=>{
                            //   this.$router.replace("/member/order/detail?id=" + order_id);
                            // }).catch(()=>{
                            //   this.$router.replace(
                            //     "/member/order/detail?id=" + order_id
                            //   );
                            // })
                        }
                    })
            }

        }


        // .catch(err => {
        //   this.$toast.fail(err.msg || "下单失败");
        // });
    }
  }
};
</script>

<style lang="scss">
.confirm-page {
  .address-item {
    .has-address {
      padding: 5px;
    }
    .no-address {
      line-height: 3em;
      color: #999;
    }
  }
  .van-card {
    background: #fff;
  }
}
    .order{
        /*border: solid 1px red;*/
        color: #555555;
        vertical-align: middle;
        background-color: #ffffff;
        border: 1px solid #cccccc;
        border-radius: 4px;
        -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
        box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
        -webkit-transition: border-color ease-in-out .15s, box-shadow ease-in-out .15s;
        transition: border-color ease-in-out .15s, box-shadow ease-in-out .15s;
    }
    .order:focus {
    border-color: #66afe9;
    outline: 0;
    -webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(102, 175, 233, 0.6);
    box-shadow: inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(102, 175, 233, 0.6);
}
    .order1{
        border: none;
    }
.store{
    /*border: solid 1px red;*/
    color: #555555;
    vertical-align: middle;
    background-color: #ffffff;
    border: 1px solid #cccccc;
    border-radius: 4px;
    -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
    box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
    -webkit-transition: border-color ease-in-out .15s, box-shadow ease-in-out .15s;
    transition: border-color ease-in-out .15s, box-shadow ease-in-out .15s;
}
.store:focus {
    border-color: #66afe9;
    outline: 0;
    -webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(102, 175, 233, 0.6);
    box-shadow: inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(102, 175, 233, 0.6);
}

   .store1{
    border: none;
   }
    .popup{
        height: 30%;
        overflow: scroll;
    }
</style>
